﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Api.Hub.MessageHandlers
{
    /// <summary>
    /// 某些网关设备不支持Delete方法，通过下面的方法间接实现Delete操作
    /// 1.客户端提交Post请求
    /// 2.客户端的请求头添加ex_op=delete
    /// </summary>
    public class FixDeleteOperationHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            this.Fix(request);
            return base.SendAsync(request, cancellationToken);
        }

        private void Fix(HttpRequestMessage request)
        {
            if (request.Method == HttpMethod.Post)
            {
                IEnumerable<string> headers = new List<string>();
                if (request.Headers.TryGetValues("ex_op", out headers) && headers.Any())
                {
                    var op = headers.First();
                    if (!string.IsNullOrEmpty(op) && op.ToLower() == "delete")
                    {
                        request.Method = HttpMethod.Delete;
                    }
                }
            }
        }
    }
}
